package com.videoaggre.zcl.ui.widget

import android.content.Context
import android.os.SystemClock
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
import com.tencent.smtt.export.external.interfaces.WebResourceResponse
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.videoaggre.zcl.BuildConfig
import com.videoaggre.zcl.parse.IParse
import com.videoaggre.zcl.utils.Logger

class X5WebView : WebView {
    var mIParse: IParse? = null
        set(value) {
            field = value
            value?.injectCancel {
                stopLoading()
                field = null
            }
            value?.start()
            loadUrl(value?.url())
        }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        settings.run {
            builtInZoomControls = false
            setSupportZoom(false)
            setDisplayZoomControls(false)
            setJavaScriptEnabled(true)
            javaScriptCanOpenWindowsAutomatically = true
            defaultTextEncodingName = "UTF-8"
            allowFileAccess = true
            setSupportMultipleWindows(true)
            loadsImagesAutomatically = false
//        setUseWideViewPort(true)
//        setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS)
            val appCacheDir = context.getDir("cache", Context.MODE_PRIVATE).path
            setAppCachePath(appCacheDir)
            cacheMode = WebSettings.LOAD_DEFAULT
            domStorageEnabled = true
            databaseEnabled = true
            setAppCacheEnabled(true)
            if (BuildConfig.DEBUG) {
                setWebContentsDebuggingEnabled(true)
            }
            mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW;
        }
//        webSettings.setUserAgent(webSettings.getUserAgentString() + Key.USER_AGENT)
        if (x5WebViewExtension != null) {
            x5WebViewExtension.setScrollBarFadingEnabled(false)
        }
        isHorizontalScrollBarEnabled = false
        isVerticalScrollBarEnabled = false
        overScrollMode = OVER_SCROLL_NEVER
        webViewClient = WebViewClient()
        addJavascriptInterface(Jsbridge(), "Jsbridge")
        setOnLongClickListener { true }
    }

    inner class WebViewClient : com.tencent.smtt.sdk.WebViewClient() {
        override fun onPageFinished(webView: WebView, url: String) {
            //setTimeout(function () {Jsbridge.html(document.getElementsByTagName('html')[0].innerHTML)},2000)
//            webView.evaluateJavascript("""javascript:Jsbridge.html(document.getElementsByTagName('html')[0].innerHTML)""") {}
//            webView.evaluateJavascript("""javascript:setTimeout(function () {Jsbridge.html(document.getElementsByTagName('html')[0].innerHTML)},2000)""") {}
            //$("body").css("background","#ffffff")
            mIParse?.onPageFinished(webView, url)
        }

        override fun onReceivedError(p0: WebView?, p1: Int, p2: String?, p3: String?) {
            mIParse?.error()
        }

        override fun shouldInterceptRequest(webView: WebView?, url: String?): WebResourceResponse? {
            mIParse?.shouldInterceptRequest(url ?: "")
            return super.shouldInterceptRequest(webView, url)
        }

        override fun shouldOverrideUrlLoading(webView: WebView, url: String): Boolean {
            webView.loadUrl(url)
            return true
        }
    }

    inner class Jsbridge {
        @JavascriptInterface
        open fun html(html: String) {
//            stopLoading()
            mIParse?.success(html)
            if (mIParse?.successDestroy == true)
                mIParse = null
        }
    }
}